﻿using DevExpress.XtraLayout.Utils;
using DevExpress.XtraTreeList.Nodes;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Windows.Forms;
using XuanFe.AppLaunch.Common;
using XuanFe.Database.BLL;
using XuanFe.Database.DAL;
using XuanFe.Database.Model;

namespace XuanFe.AppLaunch
{
    public partial class RoleForm : DevExpress.XtraEditors.XtraForm
    {
        private const string m_ModuleId = "0102";

        private int colIndexID = 0;
        private int colIndexNAME = 0;
        private int colIndexLEVEL = 0;
        private int colIndexFOLLOW_FLG = 0;

        private List<ModuleModel> m_modules;
        private List<FunctionModel> m_functions;
        private List<RoleModuleModel> m_roleModules;
        private List<RoleFunctionModel> m_roleFunctions;
        private ManageState m_ManageState;

        public RoleForm()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 设置界面状态
        /// </summary>
        /// <param name="state"></param>
        private void SetManageState(ManageState state)
        {
            this.m_ManageState = state;

            this.errorProvider1.ClearErrors();

            switch (state)
            {
                case ManageState.None:
                    this.gridControl1.Enabled = true;

                    this.btnAppend.Enabled = true;
                    this.btnModify.Enabled = false;
                    this.btnDelete.Enabled = false;
                    this.btnSave.Enabled = false;
                    this.btnCancel.Enabled = true;
                    this.btnCancel.Text = "关闭(&C)";

                    this.txtId.Text = string.Empty;
                    this.txtName.Text = string.Empty;
                    this.seLevel.Value = LoginInfo.Instance.StaffLogon.Role.Level;
                    this.chkFollow.Checked = true;
                    this.tlFunctions.UncheckAll();

                    this.txtId.Enabled = false;
                    this.txtName.Enabled = false;
                    this.seLevel.Enabled = false;
                    this.chkFollow.Enabled = false;
                    this.tlFunctions.Enabled = false;
                    break;
                case ManageState.Append:
                    this.gridControl1.Enabled = false;

                    this.btnAppend.Enabled = false;
                    this.btnModify.Enabled = false;
                    this.btnDelete.Enabled = false;
                    this.btnSave.Enabled = true;
                    this.btnCancel.Enabled = true;
                    this.btnCancel.Text = "取消(&C)";

                    this.txtId.Text = string.Empty;
                    this.txtName.Text = string.Empty;
                    this.seLevel.Value = LoginInfo.Instance.StaffLogon.Role.Level;
                    this.chkFollow.Checked = true;
                    this.tlFunctions.CheckAll();

                    this.txtId.Enabled = true;
                    this.txtName.Enabled = true;
                    this.seLevel.Enabled = true;
                    this.chkFollow.Enabled = true;
                    this.tlFunctions.Enabled = true;

                    this.txtId.Focus();
                    break;
                case ManageState.Modify:
                    this.gridControl1.Enabled = false;

                    this.btnAppend.Enabled = false;
                    this.btnModify.Enabled = false;
                    this.btnDelete.Enabled = false;
                    this.btnSave.Enabled = true;
                    this.btnCancel.Enabled = true;
                    this.btnCancel.Text = "取消(&C)";

                    this.txtId.Enabled = false;
                    this.txtName.Enabled = true;
                    this.seLevel.Enabled = true;
                    this.chkFollow.Enabled = true;
                    this.tlFunctions.Enabled = true;

                    this.txtName.Focus();
                    break;
                case ManageState.Delete:
                    this.gridControl1.Enabled = false;

                    this.btnAppend.Enabled = false;
                    this.btnModify.Enabled = false;
                    this.btnDelete.Enabled = false;
                    this.btnSave.Enabled = false;
                    this.btnCancel.Enabled = false;

                    this.txtId.Enabled = false;
                    this.txtName.Enabled = false;
                    this.seLevel.Enabled = false;
                    this.chkFollow.Enabled = false;
                    this.tlFunctions.Enabled = false;
                    break;
                case ManageState.Save:
                    this.gridControl1.Enabled = false;

                    this.btnAppend.Enabled = false;
                    this.btnModify.Enabled = false;
                    this.btnDelete.Enabled = false;
                    this.btnSave.Enabled = false;
                    this.btnCancel.Enabled = false;

                    this.txtId.Enabled = false;
                    this.txtName.Enabled = false;
                    this.seLevel.Enabled = false;
                    this.chkFollow.Enabled = false;
                    this.tlFunctions.Enabled = false;
                    break;
                case ManageState.Browse:
                case ManageState.Cancel:
                    this.gridControl1.Enabled = true;

                    this.btnAppend.Enabled = true;
                    this.btnModify.Enabled = this.IsModify();
                    this.btnDelete.Enabled = this.IsDelete();
                    this.btnSave.Enabled = false;
                    this.btnCancel.Enabled = true;
                    this.btnCancel.Text = "关闭(&C)";

                    this.txtId.Text = string.Empty;
                    this.txtName.Text = string.Empty;
                    this.seLevel.Value = LoginInfo.Instance.StaffLogon.Role.Level;

                    this.txtId.Enabled = false;
                    this.txtName.Enabled = false;
                    this.seLevel.Enabled = false;
                    this.chkFollow.Enabled = false;
                    this.tlFunctions.Enabled = false;

                    this.gridView1_SelectionChanged(null, null);
                    break;
                default:
                    this.gridControl1.Enabled = false;

                    this.btnAppend.Enabled = false;
                    this.btnModify.Enabled = false;
                    this.btnDelete.Enabled = false;
                    this.btnSave.Enabled = false;
                    this.btnCancel.Enabled = false;

                    this.txtId.Enabled = false;
                    this.txtName.Enabled = false;
                    this.seLevel.Enabled = false;
                    this.chkFollow.Enabled = false;
                    this.tlFunctions.Enabled = false;
                    break;
            }
        }

        private bool IsModify()
        {
            return (this.gridView1.RowCount > 0 && this.gridView1.FocusedRowHandle >= 0);
        }

        private bool IsDelete()
        {
            return (this.gridView1.RowCount > 0 && this.gridView1.FocusedRowHandle >= 0);
        }

        /// <summary>
        /// 清空记录
        /// </summary>
        private void ClearRecordToGrid()
        {
            this.gridView1.BeginUpdate();
            this.gridView1.Columns.Clear();

            DevExpress.XtraGrid.Columns.GridColumn c;
            int visibleIndex = 0;

            this.colIndexID = this.gridView1.Columns.Count;
            c = new DevExpress.XtraGrid.Columns.GridColumn();
            c.FieldName = "ROLE_ID";
            c.Caption = "编码";
            c.Fixed = DevExpress.XtraGrid.Columns.FixedStyle.Left;
            c.OptionsColumn.ReadOnly = true;
            c.OptionsColumn.AllowFocus = false;
            c.Visible = true;
            c.VisibleIndex = visibleIndex++;
            c.Summary.AddRange(new DevExpress.XtraGrid.GridSummaryItem[] {
            new DevExpress.XtraGrid.GridColumnSummaryItem(DevExpress.Data.SummaryItemType.Custom, "ROLE_ID", "总数")});
            this.gridView1.Columns.Add(c);

            this.colIndexNAME = this.gridView1.Columns.Count;
            c = new DevExpress.XtraGrid.Columns.GridColumn();
            c.FieldName = "ROLE_NAME";
            c.Caption = "描述";
            c.Fixed = DevExpress.XtraGrid.Columns.FixedStyle.Left;
            c.OptionsColumn.ReadOnly = true;
            c.OptionsColumn.AllowFocus = false;
            c.Visible = true;
            c.VisibleIndex = visibleIndex++;
            c.Summary.AddRange(new DevExpress.XtraGrid.GridSummaryItem[] {
            new DevExpress.XtraGrid.GridColumnSummaryItem(DevExpress.Data.SummaryItemType.Count)});
            this.gridView1.Columns.Add(c);

            this.colIndexLEVEL = this.gridView1.Columns.Count;
            c = new DevExpress.XtraGrid.Columns.GridColumn();
            c.FieldName = "ROLE_LEVEL";
            c.Caption = "级别";
            c.OptionsColumn.ReadOnly = true;
            c.OptionsColumn.AllowFocus = false;
            c.Visible = true;
            c.VisibleIndex = visibleIndex++;
            this.gridView1.Columns.Add(c);

            this.colIndexFOLLOW_FLG = this.gridView1.Columns.Count;
            c = new DevExpress.XtraGrid.Columns.GridColumn();
            c.FieldName = "FOLLOW_FLG";
            c.Caption = "允许跟进订单?";
            c.OptionsColumn.ReadOnly = true;
            c.OptionsColumn.AllowFocus = false;
            c.Visible = true;
            c.VisibleIndex = visibleIndex++;
            this.gridView1.Columns.Add(c);

            this.gridView1.EndUpdate();
        }

        /// <summary>
        /// 加载记录
        /// </summary>
        private void LoadRecordToGrid()
        {
            this.BuildAll();

            using (DataSet ds = RoleDAL.Instance.GetDataSet(LoginInfo.Instance.StaffLogon.Role.Level))
            {
                this.gridControl1.DataSource = ds.Tables[0];
                this.gridView1.BestFitColumns();

                if (this.gridView1.RowCount > 0)
                {
                    this.SetManageState(ManageState.Browse);
                }
                else
                {
                    this.SetManageState(ManageState.None);
                }
            }
        }
        private void InitAll()
        {
            this.m_modules = ModuleDAL.Instance.Gets();
            this.m_functions = FunctionDAL.Instance.Gets();
        }
        private void BuildAll()
        {
        }
        private void BuildFunctions(string roleId)
        {
            this.m_roleModules = RoleModuleDAL.Instance.Get(roleId);
            this.m_roleFunctions = RoleFunctionDAL.Instance.Get(roleId);

            this.tlFunctions.Nodes.Clear();
            this.BuildModule(this.tlFunctions.Nodes, "00");
            this.tlFunctions.ExpandAll();
        }
        private void BuildModule(TreeListNodes nodes, string parentModuleId)
        {
            List<ModuleModel> list = (from m in LoginInfo.Instance.StaffLogon.Modules where m.ParentId == parentModuleId orderby m.SortIndex select m).ToList();
            int checkedCount = 0;
            int uncheckedCount = 0;
            foreach (ModuleModel item in list)
            {
                TreeListNode node = nodes.Add(new object[] { item });
                node.Tag = item;
                this.BuildModule(node.Nodes, item.Id);
                if (!node.HasChildren)
                {
                    this.BuildFunction(node.Nodes, item.Id);
                }
                switch (node.CheckState)
                {
                    case CheckState.Checked: checkedCount++; break;
                    case CheckState.Unchecked: uncheckedCount++; break;
                }
            }
            if (nodes.ParentNode != null)
            {
                if (nodes.Count == checkedCount)
                {
                    nodes.ParentNode.CheckState = CheckState.Checked;
                }
                else if (nodes.Count == uncheckedCount)
                {
                    nodes.ParentNode.CheckState = CheckState.Unchecked;
                }
                else
                {
                    nodes.ParentNode.CheckState = CheckState.Indeterminate;
                }
            }
        }
        private void BuildFunction(TreeListNodes nodes, string moduleId)
        {
            List<ModuleModel> list = (from f in LoginInfo.Instance.StaffLogon.Functions where f.ModuleId == moduleId orderby f.SortIndex select new ModuleModel() { Id = f.Id, Name = f.Name, ParentId = f.ModuleId, SortIndex = f.SortIndex }).ToList();
            int checkedCount = 0;
            foreach (ModuleModel item in list)
            {
                TreeListNode node = nodes.Add(new object[] { item });
                node.Tag = item;
                node.Checked = this.m_roleFunctions.FindIndex((f) => { return string.Equals(f.FunctionId, item.Id); }) != -1;
                if (node.Checked)
                {
                    checkedCount++;
                }
            }
            if (checkedCount == 0)
            {
                nodes.ParentNode.CheckState = CheckState.Unchecked;
            }
            else
            {
                nodes.ParentNode.CheckState = nodes.Count != checkedCount ? CheckState.Indeterminate : CheckState.Checked;
            }
        }

        /// <summary>
        /// 添加记录
        /// </summary>
        /// <returns></returns>
        private bool AppendRecord()
        {
            try
            {
                RoleModel model = new RoleModel()
                {
                    Id = this.txtId.Text.Trim(),
                    Name = this.txtName.Text.Trim(),
                    Level = Convert.ToInt32(this.seLevel.Value),
                    Follow = this.chkFollow.Checked,
                    LastModifiedStaffId = LoginInfo.Instance.StaffLogon.Staff.Id,
                    LastModifiedDate = DateTime.Now,
                };

                using (DbConnection conn = MySQLHelper.Instance.CreateConnection())
                {
                    try
                    {
                        if (conn.State != ConnectionState.Open)
                            conn.Open();

                        DbTransaction tran = conn.BeginTransaction();
                        try
                        {
                            RoleDAL.Instance.Insert(tran, model);

                            this.tlFunctions.LoopTree((item) =>
                            {
                                if (item.CheckState == CheckState.Unchecked) return;

                                ModuleModel module = item.Tag as ModuleModel;
                                if (item.HasChildren)
                                {
                                    // 模块
                                    RoleModuleDAL.Instance.Insert(tran, new RoleModuleModel() { RoleId = model.Id, ModuleId = module.Id, LastModifiedStaffId = model.LastModifiedStaffId, LastModifiedDate = model.LastModifiedDate });
                                }
                                else
                                {
                                    // 功能
                                    RoleFunctionDAL.Instance.Insert(tran, new RoleFunctionModel() { RoleId = model.Id, FunctionId = module.Id, LastModifiedStaffId = model.LastModifiedStaffId, LastModifiedDate = model.LastModifiedDate });
                                }
                            });

                            tran.Commit();
                            return (true);
                        }
                        catch
                        {
                            tran.Rollback();
                            return (false);
                        }
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
            }
            catch
            {
                return (false);
            }
        }

        /// <summary>
        /// 修改记录
        /// </summary>
        /// <returns></returns>
        private bool ModifyRecord()
        {
            try
            {
                RoleModel model = new RoleModel()
                {
                    Id = this.txtId.Text.Trim(),
                    Name = this.txtName.Text.Trim(),
                    Level = Convert.ToInt32(this.seLevel.Value),
                    Follow = this.chkFollow.Checked,
                    LastModifiedStaffId = LoginInfo.Instance.StaffLogon.Staff.Id,
                    LastModifiedDate = DateTime.Now,
                };

                using (DbConnection conn = MySQLHelper.Instance.CreateConnection())
                {
                    try
                    {
                        if (conn.State != ConnectionState.Open)
                            conn.Open();

                        DbTransaction tran = conn.BeginTransaction();
                        try
                        {
                            RoleDAL.Instance.Update(tran, model);
                            RoleModuleDAL.Instance.Delete(tran, model.Id);
                            RoleFunctionDAL.Instance.Delete(tran, model.Id);

                            this.tlFunctions.LoopTree((item) =>
                            {
                                if (item.CheckState == CheckState.Unchecked) return;

                                ModuleModel module = item.Tag as ModuleModel;
                                if (item.HasChildren)
                                {
                                    // 模块
                                    RoleModuleDAL.Instance.Insert(tran, new RoleModuleModel() { RoleId = model.Id, ModuleId = module.Id, LastModifiedStaffId = model.LastModifiedStaffId, LastModifiedDate = model.LastModifiedDate });
                                }
                                else
                                {
                                    // 功能
                                    RoleFunctionDAL.Instance.Insert(tran, new RoleFunctionModel() { RoleId = model.Id, FunctionId = module.Id, LastModifiedStaffId = model.LastModifiedStaffId, LastModifiedDate = model.LastModifiedDate });
                                }
                            });

                            tran.Commit();
                            return (true);
                        }
                        catch
                        {
                            tran.Rollback();
                            return (false);
                        }
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
            }
            catch
            {
                return (false);
            }
        }

        /// <summary>
        /// 删除记录
        /// </summary>
        /// <param name="Code"></param>
        /// <returns></returns>
        private bool DeleteRecord(string Code)
        {
            try
            {
                using (DbConnection conn = MySQLHelper.Instance.CreateConnection())
                {
                    try
                    {
                        if (conn.State != ConnectionState.Open)
                            conn.Open();

                        DbTransaction tran = conn.BeginTransaction();
                        try
                        {
                            RoleDAL.Instance.Delete(tran, Code);
                            RoleModuleDAL.Instance.Delete(tran, Code);
                            RoleFunctionDAL.Instance.Delete(tran, Code);

                            tran.Commit();
                            return (true);
                        }
                        catch
                        {
                            tran.Rollback();
                            return (false);
                        }
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
            }
            catch
            {
                return (false);
            }
        }

        /// <summary>
        /// 记录是否正在使用
        /// </summary>
        /// <param name="UrlCd"></param>
        /// <returns></returns>
        private bool RecordIsUsing(string Code)
        {
            if (!StaffDAL.Instance.RoleUsing(Code))
                return false;
            return true;
        }

        /// <summary>
        /// 记录是否已存在
        /// </summary>
        /// <param name="UrlCd"></param>
        /// <returns></returns>
        private bool RecordIsExist(string Code)
        {
            if (RoleDAL.Instance.Exist(Code))
                return (true);

            return (false);
        }
        /// <summary>
        /// 获取最大的编码
        /// </summary>
        /// <param name="dataTable">数据源</param>
        /// <param name="columnName">数据源列名</param>
        /// <returns></returns>
        private string GetMaxId(DataTable dataTable, string columnName)
        {
            string result = "001";
            if (dataTable == null) return result;
            int count = dataTable.Rows.Count;

            // 获取最大的长度
            int maxlen = 0;
            for (int i = 0; i < count; i++)
            {
                string v = dataTable.Rows[i][columnName].ToString();
                if (v.Length > maxlen)
                    maxlen = v.Length;
            }

            // 获取最大长度的记录，并排序
            DataRow[] rows = dataTable.Select(string.Format("len({0})={1}", columnName, maxlen), string.Format("{0} desc", columnName));
            count = rows.Length;
            if (count == 0) return result;

            // 获取第一条记录
            string maxid = rows[0][columnName].ToString();
            if (Global.Instance.IsInt(maxid))
            {
                // 整型，直接累计并返回
                result = Convert.ToString(Convert.ToDecimal(maxid) + 1).PadLeft(maxid.Length, '0');
            }
            else
            {
                // 非整型，截取最右边为数字那部分
                string code = string.Empty;
                for (int i = maxid.Length - 1; i >= 0; i--)
                {
                    char c = maxid[i];
                    if (Char.IsNumber(c))
                    {
                        code = string.Concat(c.ToString(), code);
                        continue;
                    }
                    break;
                }
                if (!string.IsNullOrEmpty(code))
                {
                    // 成功截取最右边数字部分
                    result = string.Concat(maxid.Substring(0, maxid.Length - code.Length), Convert.ToString(Convert.ToDecimal(code) + 1).PadLeft(code.Length, '0'));
                }
                else
                {
                    // 截取失败
                    result = string.Concat(maxid, "1");
                }
            }
            return result;
        }
        /// <summary>
        /// 描述是否已经存在
        /// </summary>
        /// <param name="Code"></param>
        /// <param name="Desc"></param>
        /// <returns></returns>
        private bool DescriptionIsExist(string Code, string Desc)
        {
            if (RoleDAL.Instance.Exist(Code, Desc))
                return (true);

            return (false);
        }
        /// <summary>
        /// 有效性校验
        /// </summary>
        /// <returns></returns>
        private bool ValidityCheck()
        {
            this.errorProvider1.ClearErrors();
            string message = string.Empty;
            if (Global.Instance.MandatoryFieldEmpty(this.txtId, false, ref message))
            {
                this.errorProvider1.SetError(this.txtId, message);
                this.txtId.Focus();
                return (false);
            }
            if (Global.Instance.MandatoryFieldEmpty(this.txtName, false, ref message))
            {
                this.errorProvider1.SetError(this.txtName, message);
                this.txtName.Focus();
                return (false);
            }
            if (this.DescriptionIsExist(this.txtId.Text.Trim(), this.txtName.Text.Trim()))
            {
                this.errorProvider1.SetError(this.txtName, "该记录已存在！");
                this.txtName.Focus();
                return (false);
            }
            bool isChecked = false;
            foreach (TreeListNode node in this.tlFunctions.Nodes)
            {
                node.LoopTreeNodes_Break((item) =>
                {
                    if(item.CheckState != CheckState.Unchecked)
                    {
                        isChecked = true;
                        return false;// 跳出循环
                    }
                    return true; // 继续循环
                });
                if (isChecked) break;
            }
            if (!isChecked)
            {
                this.errorProvider1.SetError(this.tlFunctions, "请选择权限！");
                this.tlFunctions.Focus();
                return (false);
            }
            return (true);
        }

        private bool CheckSelected()
        {
            return (this.gridView1.SelectedRowsCount > 0);
        }

        private void RoleForm_Load(object sender, EventArgs e)
        {
            try
            {
                this.SetManageState(ManageState.None);
                this.seLevel.Properties.MinValue = LoginInfo.Instance.StaffLogon.Role.Level;

                this.InitAll();
                this.ClearRecordToGrid();

                this.LoadRecordToGrid();

                StaffLogBLL.Instance.InsertLog(LoginInfo.Instance.StaffLogon.Staff.Id, m_ModuleId, "浏览记录");

                // 新增角色信息
                if (!LoginInfo.Instance.CheckPermission("010202"))
                {
                    this.lcAppend.Visibility = LayoutVisibility.Never;
                }
                // 修改角色信息
                if (!LoginInfo.Instance.CheckPermission("010203"))
                {
                    this.lcModify.Visibility = LayoutVisibility.Never;
                }
                // 删除角色信息
                if (!LoginInfo.Instance.CheckPermission("010204"))
                {
                    this.lcDelete.Visibility = LayoutVisibility.Never;
                }
                if (this.lcAppend.Visibility == LayoutVisibility.Never
                    && this.lcModify.Visibility == LayoutVisibility.Never)
                {
                    this.lcSave.Visibility = LayoutVisibility.Never;
                }
            }
            catch (Exception ex)
            {
                Global.Instance.ShowExceptionDlg(ex);
            }
        }

        private void gridView1_SelectionChanged(object sender, DevExpress.Data.SelectionChangedEventArgs e)
        {
            try
            {
                if (this.gridView1.SelectedRowsCount != 1) return;

                int r = this.gridView1.GetSelectedRows()[0];
                if (r < 0)
                {
                    this.btnModify.Enabled = false;
                    this.btnDelete.Enabled = false;
                    return;
                }
                this.btnModify.Enabled = true;
                this.btnDelete.Enabled = true;

                string roleId = Convert.ToString(this.gridView1.GetRowCellValue(r, this.gridView1.Columns[this.colIndexID]));
                this.txtId.Text = roleId;
                this.txtName.Text = Convert.ToString(this.gridView1.GetRowCellValue(r, this.gridView1.Columns[this.colIndexNAME]));
                this.seLevel.Value = Convert.ToInt32(this.gridView1.GetRowCellValue(r, this.gridView1.Columns[this.colIndexLEVEL]));
                this.chkFollow.Checked = string.Equals(Convert.ToString(this.gridView1.GetRowCellValue(r, this.gridView1.Columns[this.colIndexFOLLOW_FLG])), "Y");

                this.BuildFunctions(roleId);
            }
            catch (Exception ex)
            {
                Global.Instance.ShowExceptionDlg(ex);
            }
        }

        private void btnAppend_Click(object sender, EventArgs e)
        {
            try
            {
                this.SetManageState(ManageState.Append);
                this.txtId.Text = this.GetMaxId(this.gridControl1.DataSource as DataTable, this.gridView1.Columns[this.colIndexID].FieldName);
                this.txtId.SelectAll();
            }
            catch (Exception ex)
            {
                Global.Instance.ShowExceptionDlg(ex);
            }
        }

        private void btnModify_Click(object sender, EventArgs e)
        {
            try
            {
                if (!this.CheckSelected())
                {
                    Global.Instance.InfoDlg("没有可选的记录！");
                    return;
                }
                this.SetManageState(ManageState.Modify);
            }
            catch (Exception ex)
            {
                Global.Instance.ShowExceptionDlg(ex);
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                if (!this.CheckSelected())
                {
                    Global.Instance.InfoDlg("没有可选的记录！");
                    return;
                }

                if (!Global.Instance.QueryDlg("是否真的要删除所选的记录？")) return;

                Global.Instance.BeginWait();
                this.progressBar1.EditValue = 0;
                this.lciProgressBar.ContentVisible = true;

                int UsingCount = 0, FailedCount = 0;
                double step = 100.00 / this.gridView1.SelectedRowsCount;
                double total = 0;
                foreach (int r in this.gridView1.GetSelectedRows())
                {
                    total += step;
                    this.progressBar1.EditValue = Convert.ToInt32(Math.Round(total));
                    Application.DoEvents();

                    if (r < 0) continue;
                    string id = this.gridView1.GetRowCellValue(r, this.gridView1.Columns[this.colIndexID]).ToString();
                    if (!this.RecordIsUsing(id))
                    {
                        if (!this.DeleteRecord(id))
                        {
                            FailedCount++;
                            continue;
                        }
                        StaffLogBLL.Instance.InsertLog(LoginInfo.Instance.StaffLogon.Staff.Id, m_ModuleId, string.Format("删除编码为“{0}”的记录", id));
                    }
                    else
                    {
                        UsingCount++;
                    }
                }

                if (UsingCount > 0 || FailedCount > 0)
                    Global.Instance.WarningDlg(string.Format("删除完毕！其中有{0}条记录正在使用，{1}条记录删除失败.", UsingCount, FailedCount));

                this.LoadRecordToGrid();
            }
            catch (Exception ex)
            {
                Global.Instance.ShowExceptionDlg(ex);
            }
            finally
            {
                this.progressBar1.EditValue = 100;
                this.lciProgressBar.ContentVisible = false;
                Global.Instance.EndWait();
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (!this.ValidityCheck()) return;

                Global.Instance.BeginWait();
                ManageState state = this.m_ManageState;

                string id = this.txtId.Text.Trim();
                switch (state)
                {
                    case ManageState.Append:
                        if (this.RecordIsExist(id))
                        {
                            this.errorProvider1.SetError(this.txtId, "该记录已存在！");
                            this.txtId.Focus();
                            return;
                        }

                        if (!this.AppendRecord())
                        {
                            Global.Instance.ErrorDlg("保存失败！");
                            return;
                        }
                        StaffLogBLL.Instance.InsertLog(LoginInfo.Instance.StaffLogon.Staff.Id, m_ModuleId, string.Format("新增编码为“{0}”的记录", id));
                        break;
                    case ManageState.Modify:
                        if (!this.ModifyRecord())
                        {
                            Global.Instance.ErrorDlg("保存失败！");
                            return;
                        }
                        StaffLogBLL.Instance.InsertLog(LoginInfo.Instance.StaffLogon.Staff.Id, m_ModuleId, string.Format("修改编码为“{0}”的记录", id));
                        break;
                }

                this.LoadRecordToGrid();
            }
            catch (Exception ex)
            {
                Global.Instance.ShowExceptionDlg(ex);
            }
            finally
            {
                Global.Instance.EndWait();
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.m_ManageState == ManageState.Append || this.m_ManageState == ManageState.Modify)
                {
                    this.SetManageState(ManageState.Cancel);
                    this.errorProvider1.ClearErrors();
                }
                else
                {
                    this.Close();
                }
            }
            catch (Exception ex)
            {
                Global.Instance.ShowExceptionDlg(ex);
            }
        }

        private void gridView1_RowCountChanged(object sender, EventArgs e)
        {
            try
            {
                this.gridView1.SelectRow(this.gridView1.FocusedRowHandle);
                this.btnModify.Enabled = this.IsModify();
                this.btnDelete.Enabled = this.IsDelete();
            }
            catch (Exception ex)
            {
                Global.Instance.ShowExceptionDlg(ex);
            }
        }

        private void tlFunctions_BeforeCheckNode(object sender, DevExpress.XtraTreeList.CheckNodeEventArgs e)
        {
            e.State = (e.PrevState == CheckState.Checked ? CheckState.Unchecked : CheckState.Checked);
        }

        private void tlFunctions_AfterCheckNode(object sender, DevExpress.XtraTreeList.NodeEventArgs e)
        {
            e.Node.ProcessNodeCheckState(e.Node.CheckState);
        }
    }
}
